package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登陆请求
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        HashMap<String, String> header = new HashMap<>();

        Map<String,String> map = new HashMap<>();
        map.put("client_id","4104494291");
        map.put("client_secret","2613e50a61a46a8aa96a19c4854f822c");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //1.根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, null, map);
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //判断用户是否第一次登陆，第一次登陆注册入库
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode()==0){
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {});
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                //2.登陆成功跳回首页
                return "redirect:http://gulimall.com";
            }else {
                return "";
            }
        }else {
            return "redirect:http://gulimall.com/login.html";
        }
    }
}
